#! /bin/sh

# Apache configuration script, first cut --- rst.
# Dont like it?  Inspired to do something better?  Go for it.

file=Configuration
tmpfile=htconf.$$

if [ "x$1" = "x-file" ] ; then
  echo "Using alternate config file $2"
  file=$2 
else
  echo "Using 'Configuration' as config file"
fi

# First, strip comments and blank lines...

sed 's/#.*//' $file | sed '/^[ 	]*$/d' | sed 's/[ 	]*$//' > $tmpfile

# Check for syntax errors...

if grep -v = $tmpfile | \
   egrep -v '^Module[ 	]+[A-Za-z0-9_]+[ 	]+[^ 	]+$' > /dev/null
then
   echo "Syntax error --- each config file command must either"
   echo "set a Makefile option, or configure a module (giving a"
   echo "module name and a filename).  This doesn't appear to be"
   echo "doing either:"
   grep -v = $tmpfile | \
      egrep -v '^Module[ 	]+[A-Za-z0-9_]+[ 	]+[^ 	]+$'
   rm $tmpfile
   exit 1
fi

# File is OK --- make backup copies of things and then get the new ones:

if [ -f Makefile ] ; then mv Makefile Makefile.bak; fi
if [ -f modules.c ] ; then mv modules.c modules.c.bak; fi

awk >modules.c <$tmpfile '\
   BEGIN { modules[n++] = "core_module" } \
   /^Module/ { modules[n++] = $2 } \
   END { print "/* modules.c --- automatically generated by Apache"; \
         print " * configuration script.  DO NOT HAND EDIT!!!!!"; \
         print " */"; \
         print ""; \
	 print "#include \"httpd.h\""; \
	 print "#include \"http_config.h\""; \
         print ""; \
         for (i = 0; i < n; ++i) { \
             printf ("extern module %s;\n", modules[i]); \
         } \
         print ""; \
         print "module *prelinked_modules[] = {"; \
         for (i = 0; i < n; ++i) { \
             printf "  &%s,\n", modules[i]; \
         } \
	 print "  NULL"; \
         print "};"; \
   }'

awk >Makefile <$tmpfile '\
   BEGIN { print "# Makefile automatically generated from Makefile.tmpl"; \
	   print "# and configuration file by Apache config script. "; \
	   print "# Hand-edited changes will be lost if the config script"; \
	   print "# is re-run."; \
         } \
   /^Module/ { modules[n++] = $3 } \
   /\=/ { print } \
   END { print "MODULES=\\"; \
         for (i = 0; i < n; ++i) { \
             if (i < n-1) printf ("  %s \\\n", modules[i]); \
             else printf ("  %s\n", modules[i]); \
         } \
         print "" \
       }'

cat Makefile.tmpl >> Makefile
rm $tmpfile
